/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.poker.Card;
import me.zhengjie.modules.poker.Player;
import me.zhengjie.modules.poker.PokerFormatUtil;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.dto.PokerUserActivatInfoQueryCriteria;
import me.zhengjie.modules.system.domain.vo.KingTeamVO;
import me.zhengjie.modules.system.domain.vo.KingTeamVoteVO;
import me.zhengjie.modules.system.mapper.PokerActivateInfoMapper;
import me.zhengjie.modules.system.mapper.PokerUserActivatInfoMapper;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import me.zhengjie.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author greazy
* @date 2025-04-07
**/
@Service
@RequiredArgsConstructor
public class PokerUserActivatInfoServiceImpl extends ServiceImpl<PokerUserActivatInfoMapper, PokerUserActivatInfo> implements PokerUserActivatInfoService {

    private final PokerUserActivatInfoMapper pokerUserActivatInfoMapper;

    private final PokerActivateInfoMapper activateInfoMapper;

    private final PokerUserServerInfoService userServerInfoService;


    private final UserService userService;

    private final KingTeamService kingTeamService;

    private final KingTeamVoteService kingTeamVoteService;

    @Override
    public PageResult<PokerUserActivatInfo> queryAll(PokerUserActivatInfoQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(pokerUserActivatInfoMapper.findAll(criteria, page));
    }

    @Override
    public List<PokerUserActivatInfo> queryAll(PokerUserActivatInfoQueryCriteria criteria){
        return pokerUserActivatInfoMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(PokerUserActivatInfo resources) {
        pokerUserActivatInfoMapper.insert(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(PokerUserActivatInfo resources) {
        PokerUserActivatInfo pokerUserActivatInfo = getById(resources.getId());
        pokerUserActivatInfo.copy(resources);
        pokerUserActivatInfoMapper.updateById(pokerUserActivatInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        pokerUserActivatInfoMapper.deleteBatchIds(ids);
    }

    @Override
    public void download(List<PokerUserActivatInfo> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PokerUserActivatInfo pokerUserActivatInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户编号", pokerUserActivatInfo.getUserId());
            map.put("活动id", pokerUserActivatInfo.getActivateId());
            map.put("steamID", pokerUserActivatInfo.getSteamId());
            map.put("筹码数量", pokerUserActivatInfo.getJettonNum());
            map.put("免费随机次数", pokerUserActivatInfo.getRandomFreeNum());
            map.put("付费随机次数", pokerUserActivatInfo.getRandomPayNum());
            map.put("poker1",  pokerUserActivatInfo.getPoker1());
            map.put("poker2",  pokerUserActivatInfo.getPoker2());
            map.put("poker3",  pokerUserActivatInfo.getPoker3());
            map.put("牌型", pokerUserActivatInfo.getPokerType());
            map.put("换牌次数", pokerUserActivatInfo.getRandomNum());
            map.put("总花费的筹码数量", pokerUserActivatInfo.getTotalPayJettonNum());
            map.put("用户排名", pokerUserActivatInfo.getRank());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional
    public ResponseEntity<Object> changeCard(String taskId, Integer activateId, Integer cardNum,Integer type) {
        Long userId = SecurityUtils.getCurrentUserId();

        LambdaQueryWrapper<PokerUserActivatInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerUserActivatInfo::getTaskId,taskId).eq(PokerUserActivatInfo::getActivateId,activateId).eq(PokerUserActivatInfo::getUserId,userId);
        //处理本次用户换牌逻辑
        PokerUserActivatInfo pokerUserActivatInfo = pokerUserActivatInfoMapper.selectOne(wrapper);
        LambdaQueryWrapper<PokerActivateInfo> acwrapper = new LambdaQueryWrapper<>();
        acwrapper.eq(PokerActivateInfo::getTaskId,taskId).eq(PokerActivateInfo::getId,activateId);
        PokerActivateInfo pokerActivateInfo = activateInfoMapper.selectOne(acwrapper);

        LambdaQueryWrapper<PokerUserServerInfo> userServerWrapper = new LambdaQueryWrapper<>();
        userServerWrapper.eq(PokerUserServerInfo::getUserId,userId).eq(PokerUserServerInfo::getServerId,pokerActivateInfo.getServerId());
        PokerUserServerInfo userServerInfo = userServerInfoService.getOne(userServerWrapper);
        //判断活动是否结束或开启
        if (!pokerActivateInfo.getRunStatus().equals(1)){
            return new ResponseEntity<>("失败了哦，不在活动时间范围内哦", HttpStatus.ACCEPTED);
        }
        //判断最大换牌次数
        if (pokerUserActivatInfo.getRandomNum()>=pokerActivateInfo.getActiveMaxChage()){
            return new ResponseEntity<>("超出最大换牌次数，无法操作", HttpStatus.ACCEPTED);
        }
        //如果是免费换牌
        if (pokerUserActivatInfo.getRandomFreeNum()>0){
            if (type ==1){
                if (cardNum==1){
                    pokerUserActivatInfo.setPoker1(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                }else if (cardNum==2){
                    pokerUserActivatInfo.setPoker2(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                }else if(cardNum == 3){
                    pokerUserActivatInfo.setPoker3(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                }
            }else if(type == 2){
                pokerUserActivatInfo.setPoker1(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                pokerUserActivatInfo.setPoker2(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                pokerUserActivatInfo.setPoker3(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
            }

            //免费换牌次数-1
            pokerUserActivatInfo.setRandomFreeNum(pokerUserActivatInfo.getRandomFreeNum()-1);
        }else if (pokerUserActivatInfo.getRandomFreeNum()==0){
            //统计本次换牌需要花费的筹码
            Integer payNum = pokerActivateInfo.getChangePokerBaseNum()+pokerUserActivatInfo.getRandomPayNum()*pokerActivateInfo.getChangePokerAddNum();
            if (userServerInfo.getJettonNum()-payNum>=0){
                if (type ==1){
                    if (cardNum==1){
                        pokerUserActivatInfo.setPoker1(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                    }else if (cardNum==2){
                        pokerUserActivatInfo.setPoker2(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                    }else if(cardNum == 3){
                        pokerUserActivatInfo.setPoker3(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                    }
                }else if(type == 2){
                    pokerUserActivatInfo.setPoker1(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                    pokerUserActivatInfo.setPoker2(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                    pokerUserActivatInfo.setPoker3(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
                }
                userServerInfo.setJettonNum(userServerInfo.getJettonNum()-payNum);
                pokerUserActivatInfo.setRandomPayNum(pokerUserActivatInfo.getRandomPayNum()+1);
                pokerUserActivatInfo.setTotalPayJettonNum(pokerUserActivatInfo.getTotalPayJettonNum()+payNum);
            }else{
                return new ResponseEntity<>("筹码不足，换牌失败", HttpStatus.ACCEPTED);
            }

        }
        //总次数+1
        userServerInfoService.updateById(userServerInfo);
        pokerUserActivatInfo.setRandomNum(pokerUserActivatInfo.getRandomNum()+1);
        pokerUserActivatInfoMapper.updateById(pokerUserActivatInfo);

        //重新计算 牌面大小，牌型，排名
        //获取公共牌
        String[] pubPoker1 = pokerActivateInfo.getPubPoker1().split("-");
        String[] pubPoker2 = pokerActivateInfo.getPubPoker2().split("-");
        Card cardPub1 = Card.fromStrings(pubPoker1[1], pubPoker1[0]);
        Card cardPub2 = Card.fromStrings(pubPoker2[1], pubPoker2[0]);
        List<Player> players = new ArrayList<>();

        LambdaQueryWrapper<PokerUserActivatInfo> usersWrapper = new LambdaQueryWrapper<>();
        usersWrapper.eq(PokerUserActivatInfo::getTaskId,taskId).eq(PokerUserActivatInfo::getActivateId,activateId);
        //处理本次用户换牌逻辑
        List<PokerUserActivatInfo> userActivatInfoList = pokerUserActivatInfoMapper.selectList(usersWrapper);
        for (PokerUserActivatInfo userActivatInfo : userActivatInfoList) {
            List<Card> hand = new ArrayList<>();
            hand.add(cardPub1);
            hand.add(cardPub2);
            String[] card1 =userActivatInfo.getPoker1().split("-");
            hand.add(Card.fromStrings(card1[1],card1[0]));
            String[] card2 =userActivatInfo.getPoker2().split("-");
            hand.add(Card.fromStrings(card2[1],card2[0]));
            String[] card3 =userActivatInfo.getPoker3().split("-");
            hand.add(Card.fromStrings(card3[1],card3[0]));
            players.add(new Player(hand,null,userActivatInfo.getUserId(),null));
        }
        PokerFormatUtil.evaluatePlayers(players);
        for (PokerUserActivatInfo userActivatInfo : userActivatInfoList) {
            for (Player player : players) {
                if (userActivatInfo.getUserId().equals(player.getUserId())){
                    userActivatInfo.setRank(player.getRank());
                    userActivatInfo.setPokerType(player.getHandType());
                    break;
                }
            }
        }
        this.updateBatchById(userActivatInfoList);
        return new ResponseEntity<>("换牌成功", HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Object> joinActive(String taskId, Integer activateId) {
        Long currentUserId = SecurityUtils.getCurrentUserId();
        User user = userService.getById(currentUserId);
        LambdaQueryWrapper<PokerUserActivatInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerUserActivatInfo::getTaskId,taskId).eq(PokerUserActivatInfo::getActivateId,activateId).eq(PokerUserActivatInfo::getUserId,user.getId());
        //处理本次用户换牌逻辑
        PokerUserActivatInfo pokerUserActivatInfoex = pokerUserActivatInfoMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(pokerUserActivatInfoex)){
            return new ResponseEntity<>("加入失败，已在活动中", HttpStatus.ACCEPTED);

        }


        LambdaQueryWrapper<PokerActivateInfo> acwrapper = new LambdaQueryWrapper<>();
        acwrapper.eq(PokerActivateInfo::getTaskId,taskId).eq(PokerActivateInfo::getId,activateId);
        PokerActivateInfo pokerActivateInfo = activateInfoMapper.selectOne(acwrapper);
        PokerUserActivatInfo pokerUserActivatInfo = new PokerUserActivatInfo();
        pokerUserActivatInfo.setUserId(user.getId());
        pokerUserActivatInfo.setUserName(user.getUsername());
        pokerUserActivatInfo.setTaskId(taskId);
        pokerUserActivatInfo.setActivateId(activateId);
        pokerUserActivatInfo.setSteamId(user.getSteamId());
        pokerUserActivatInfo.setJettonNum(0);
        pokerUserActivatInfo.setRandomFreeNum(pokerActivateInfo.getActiveFreeChage());
        pokerUserActivatInfo.setRandomPayNum(0);
        pokerUserActivatInfo.setPoker1(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
        pokerUserActivatInfo.setPoker2(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
        pokerUserActivatInfo.setPoker3(PokerFormatUtil.getRandomCard(pokerActivateInfo.getPubPoker1(),pokerActivateInfo.getPubPoker2()));
        pokerUserActivatInfo.setRandomNum(0);
        pokerUserActivatInfo.setTotalPayJettonNum(0);
        pokerUserActivatInfo.setRank(0);
        this.save(pokerUserActivatInfo);
        this.rankDo(taskId, activateId);
        return new ResponseEntity<>("加入活动成功", HttpStatus.OK);
    }

    @Override
    public void rankDo(String taskId, Integer activateId) {
        PokerActivateInfo pokerActivateInfo = activateInfoMapper.selectById(activateId);
        //重新计算 牌面大小，牌型，排名
        //获取公共牌
        String[] pubPoker1 = pokerActivateInfo.getPubPoker1().split("-");
        String[] pubPoker2 = pokerActivateInfo.getPubPoker2().split("-");
        Card cardPub1 = Card.fromStrings(pubPoker1[1], pubPoker1[0]);
        Card cardPub2 = Card.fromStrings(pubPoker2[1], pubPoker2[0]);
        List<Player> players = new ArrayList<>();

        LambdaQueryWrapper<PokerUserActivatInfo> usersWrapper = new LambdaQueryWrapper<>();
        usersWrapper.eq(PokerUserActivatInfo::getTaskId,taskId).eq(PokerUserActivatInfo::getActivateId,activateId);
        //处理本次用户换牌逻辑
        List<PokerUserActivatInfo> userActivatInfoList = pokerUserActivatInfoMapper.selectList(usersWrapper);
        for (PokerUserActivatInfo userActivatInfo : userActivatInfoList) {
            List<Card> hand = new ArrayList<>();
            hand.add(cardPub1);
            hand.add(cardPub2);
            String[] card1 =userActivatInfo.getPoker1().split("-");
            hand.add(Card.fromStrings(card1[1],card1[0]));
            String[] card2 =userActivatInfo.getPoker2().split("-");
            hand.add(Card.fromStrings(card2[1],card2[0]));
            String[] card3 =userActivatInfo.getPoker3().split("-");
            hand.add(Card.fromStrings(card3[1],card3[0]));
            players.add(new Player(hand,null,userActivatInfo.getUserId(),null));
        }
        PokerFormatUtil.evaluatePlayers(players);
        for (PokerUserActivatInfo userActivatInfo : userActivatInfoList) {
            for (Player player : players) {
                if (userActivatInfo.getUserId().equals(player.getUserId())){
                    userActivatInfo.setRank(player.getRank());
                    userActivatInfo.setPokerType(player.getHandType());
                    break;
                }
            }
        }
        this.updateBatchById(userActivatInfoList);
    }

    @Override
    public ResponseEntity<Object> activateInfo(String taskId, Integer activateId) {
        Long userId = SecurityUtils.getCurrentUserId();
        LambdaQueryWrapper<PokerUserActivatInfo> usersWrapper = new LambdaQueryWrapper<>();
        usersWrapper.eq(PokerUserActivatInfo::getTaskId,taskId).eq(PokerUserActivatInfo::getActivateId,activateId)
                .orderByAsc(PokerUserActivatInfo::getRank);
        List<PokerUserActivatInfo> userActivatInfoList = pokerUserActivatInfoMapper.selectList(usersWrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("userActivatInfoList",userActivatInfoList);

        LambdaQueryWrapper<PokerUserActivatInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PokerUserActivatInfo::getTaskId,taskId).eq(PokerUserActivatInfo::getActivateId,activateId).eq(PokerUserActivatInfo::getUserId,userId);
        PokerUserActivatInfo pokerUserActivatInfo = pokerUserActivatInfoMapper.selectOne(wrapper);
        result.put("userAcInfo",pokerUserActivatInfo);


        int total = userActivatInfoList.stream()
                .mapToInt(PokerUserActivatInfo::getTotalPayJettonNum)
                .sum();
        result.put("total",total);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
    @Override
    public ResponseEntity<Object> iKing( Integer activateId) {
        Long userId = SecurityUtils.getCurrentUserId();
        HashMap<String, Object> result = new HashMap<>();
        LambdaQueryWrapper<KingTeam> teamWrapper = new LambdaQueryWrapper<>();
        teamWrapper.eq(KingTeam::getActivateId,activateId);
        List<KingTeam> teamList = kingTeamService.list(teamWrapper);
        Integer groupTotalBianBian = teamList.stream().mapToInt(KingTeam::getBianbianVal).sum();

        PokerActivateInfo pokerActivateInfo = activateInfoMapper.selectById(activateId);
        result.put("groupTotalBianBian",groupTotalBianBian);
        result.put("activateDesc",pokerActivateInfo.getActivateDesc());
        result.put("joinGoodName",pokerActivateInfo.getJoinGoodName());
        result.put("joinGoodNum",pokerActivateInfo.getJoinGoodNum());
        ArrayList<KingTeamVO> kingTeamList = new ArrayList<KingTeamVO>();
        boolean userFound = false;

        Integer joinShow   = kingTeamVoteService.getJoinStatus(activateId,userId);

        for (KingTeam kingTeam : teamList) {
            KingTeamVO kingTeamVO = new KingTeamVO();
            BeanUtil.copyProperties(kingTeam, kingTeamVO, true);
            if (groupTotalBianBian == 0) {
                kingTeamVO.setRate(new BigDecimal(0));
            } else {
                BigDecimal bdA = new BigDecimal(kingTeam.getBianbianVal());
                BigDecimal bdB = new BigDecimal(groupTotalBianBian);
                kingTeamVO.setRate(bdA.divide(bdB, 4, RoundingMode.FLOOR));
            }
            List<KingTeamVoteVO> kingTeamVoteVOList = kingTeamVoteService.listVoteUserName(kingTeam.getActivateId(), kingTeam.getId());
            LambdaQueryWrapper<KingTeamVote> rank1Wrapper = new LambdaQueryWrapper<>();
            rank1Wrapper.eq(KingTeamVote::getActivateId,kingTeam.getActivateId()).eq(KingTeamVote::getGroupId, kingTeam.getId()).eq(KingTeamVote::getRank,1);
            KingTeamVote rank1 = kingTeamVoteService.getOne(rank1Wrapper);
            if (ObjectUtil.isNotEmpty(rank1)){
                User user = userService.findById(rank1.getUserId());
                kingTeamVO.setKingName(user.getUsername());
            }
            for (KingTeamVoteVO kingTeamVoteVO : kingTeamVoteVOList) {
                User user = userService.findById(kingTeamVoteVO.getUserId());
                String levelName = userService.getLevelName(user.getEmpiricalVal());
                kingTeamVoteVO.setLevelName(levelName);
            }
            List<Long> userList = kingTeamVoteVOList.stream().map(KingTeamVoteVO::getUserId).toList();
            if (userList.contains(userId)) {
                userFound = true;
            }
            kingTeamVoteVOList.sort(Comparator.comparingInt(KingTeamVoteVO::getRank));
            kingTeamVO.setTeamVoteVOList(kingTeamVoteVOList);
            kingTeamVO.setIsJoin(joinShow);
            kingTeamList.add(kingTeamVO);
        }

        for (KingTeamVO kingTeamVO : kingTeamList) {
            if (userFound && !kingTeamVO.getTeamVoteVOList().stream().anyMatch(vote -> vote.getUserId().equals(userId))) {
                kingTeamVO.setIsShowVote(0);
            } else {
                kingTeamVO.setIsShowVote(1);
            }
        }
        result.put("kingTeamList",kingTeamList);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Object> doVote(Integer activateId, Integer groupId, Integer bianbianVal) {
        Long userId = SecurityUtils.getCurrentUserId();

        PokerActivateInfo pokerActivateInfo = activateInfoMapper.selectById(activateId);
        LocalDateTime now = LocalDateTime.now();
        // 获取活动的结束时间
        Timestamp endTimeTimestamp = pokerActivateInfo.getEndTime();
        if (endTimeTimestamp != null) {
            LocalDateTime endTime = endTimeTimestamp.toLocalDateTime();
            if (endTime.isBefore(now)|| pokerActivateInfo.getRunStatus()==2) {
                return new ResponseEntity<>("活动已经结束啦~~", HttpStatus.ACCEPTED);
            }
        }
        LambdaQueryWrapper<PokerUserServerInfo> userserverWrapper = new LambdaQueryWrapper<>();
        userserverWrapper.eq(PokerUserServerInfo::getUserId,userId).eq(PokerUserServerInfo::getServerId,pokerActivateInfo.getServerId());
        PokerUserServerInfo one = userServerInfoService.getOne(userserverWrapper);
        if (one.getJettonNum()-bianbianVal<0){
            return new ResponseEntity<>("便便余额不足哦", HttpStatus.ACCEPTED);
        }

        LambdaQueryWrapper<KingTeamVote> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KingTeamVote::getActivateId,activateId).eq(KingTeamVote::getGroupId,groupId);
        wrapper.eq(KingTeamVote::getUserId,userId);
        KingTeamVote kingTeamVote = kingTeamVoteService.getOne(wrapper);
        if (kingTeamVote==null){
            return new ResponseEntity<>("请先选择阵容~", HttpStatus.ACCEPTED);

        }
        kingTeamVote.setBianbianVal(kingTeamVote.getBianbianVal()+bianbianVal);
        kingTeamVoteService.update(kingTeamVote);


        one.setJettonNum(one.getJettonNum()-bianbianVal);
        userServerInfoService.updateById(one);

        KingTeam kingTeam = kingTeamService.getById(groupId);
        kingTeam.setBianbianVal(kingTeam.getBianbianVal()+bianbianVal);
        kingTeamService.update(kingTeam);



        LambdaQueryWrapper<KingTeamVote> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(KingTeamVote::getActivateId,activateId).eq(KingTeamVote::getGroupId,groupId);
        List<KingTeamVote> list = kingTeamVoteService.list(wrapper2);
        list.sort(Comparator.comparingDouble(KingTeamVote::getBianbianVal).reversed());
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRank(i + 1);
        }
        kingTeamVoteService.updateBatchById(list);
        return new ResponseEntity<>("投票成功", HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Object> selectGroup(Integer activateId,Integer groupId) {
        Long userId = SecurityUtils.getCurrentUserId();
        PokerActivateInfo pokerActivateInfo = activateInfoMapper.selectById(activateId);
        LocalDateTime now = LocalDateTime.now();
        // 获取活动的结束时间
        Timestamp endTimeTimestamp = pokerActivateInfo.getEndTime();
        if (endTimeTimestamp != null) {
            LocalDateTime endTime = endTimeTimestamp.toLocalDateTime();
            if (endTime.isBefore(now)||pokerActivateInfo.getRunStatus()==2) {
                return new ResponseEntity<>("活动已经结束啦~~", HttpStatus.ACCEPTED);

            }
        }
        LambdaQueryWrapper<KingTeamVote> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KingTeamVote::getUserId,userId).eq(KingTeamVote::getActivateId,activateId).eq(KingTeamVote::getGroupId,groupId);
        KingTeamVote one = kingTeamVoteService.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(one)){
            return new ResponseEntity<>("您已经加入该阵容啦~~", HttpStatus.ACCEPTED);

        }

        KingTeamVote kingTeamVote = new KingTeamVote();
        kingTeamVote.setRank(9999);
        kingTeamVote.setBianbianVal(0);
        kingTeamVote.setUserId(userId);
        kingTeamVote.setActivateId(activateId);
        kingTeamVote.setGroupId(groupId);
        kingTeamVoteService.save(kingTeamVote);
        return new ResponseEntity<>("阵容选择完成", HttpStatus.OK);
    }


    public static String getSuit( String[] Card){
        switch (Card[0]) {
            case "梅花":
                return "diamonds";
            case "黑桃":
                return "spades";
            case "红心":
                return "hearts";
            case "方片":
                return "clubs";
        }
//        spades("黑桃"), clubs("方片"), hearts("红心"), diamonds("梅花");
        return null;
    }

    public static String getNum( String[] Card){
        switch (Card[1]) {
            case "A":
                return "A";
            case "2":
                return "two";
            case "3":
                return "three";
            case "4":
                return "four";
            case "5":
                return "five";
            case "6":
                return "six";
            case "7":
                return "seven";
            case "8":
                return "eight";
            case "9":
                return "nine";
            case "10":
                return "ten";
            case "J":
                return "J";
            case "Q":
                return "Q";
            case "K":
                return "K";
        }
//        two("2"), three("3"), four("4"), five("5"), six("6"), seven("7"), eight("8"), nine("9"), ten("10"), J("J"), Q("Q"), K("K"), A("A");
        return null;
    }
}
